package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.Student;
import service.StudentService;
import util.Page;

import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping("/list/{currentPage}")
    public String findAll(Student student, @PathVariable("currentPage") int currentPage, Model model){
        Page page = new Page();
        page.setCurrentPage(currentPage);
        // 查询总记录数
        int totalCount = studentService.count(student);
        page.setTotalCount(totalCount);
        page.setTotalPage();
        // 计算偏移量
        int offset = (currentPage - 1) * page.getPageSize();
        List<Student> students = studentService.findAll(student, offset, page.getPageSize());
        model.addAttribute("students", students);
        model.addAttribute("page", page);
        model.addAttribute("student", student);

        return "student/list";
    }

    @RequestMapping("/toadd")
    public String toAdd(){
        return "student/add";
    }

    @RequestMapping("/addSave")
    public String addStudent(Student student){
        int result = studentService.addStudent(student);
        if (result > 0){
            return "redirect:/student/list/1";
        }
        return "error";
    }

    @RequestMapping("/delete/{id}")
    public String deleteStudent(@PathVariable("id") int id){
        int result = studentService.deleteStudent(id);
        if (result > 0){
            return "redirect:/s" +
                    "" +
                    "tudent/list/1";
        }
        return "error";
    }

    @RequestMapping("/toupdate/{id}")
    public String toUpdate(@PathVariable("id") int id,Model model){
        Student student = studentService.findStudentById(id);
        model.addAttribute("student", student);
        return "student/update";
    }

    @RequestMapping("/updateSave")
    public String updateStudent(Student student){
        int result = studentService.updateStudent(student);
        if (result > 0){
            return "redirect:/student/list/1";
        }
        return "error";
    }
}
